//
//  IGCommunityDetailVC.m
//  jingdongfang
//
//  Created by BOE on 2017/8/21.
//  Copyright © 2017年 LJL. All rights reserved.
//

#import "IGCommunityDetailVC.h"
#import "IGCommunityDetailHeaderCell.h"
#import "IGIssueTopicVC.h"
#import "IGTopicDetailVC.h"
#import "IGCommunityDetailApi.h"
#import "IGCommonApi.h"
#import "YXScrollowActionSheet.h"
#import "IGNetReachable.h"

@interface IGCommunityDetailVC ()

@property (nonatomic, strong) IGCommunityDetailApi *communityDetailApi;
@property (nonatomic, copy) NSString *lastTimeDate;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) IGCommunityModel *communityModel;
@property (nonatomic, copy) NSString *cid;
@property (nonatomic, assign) GROUP_TITLE_TYPE type;

@end

@implementation IGCommunityDetailVC

- (instancetype)initWithCid:(NSString *)cid
{
    self = [super init];
    if (self) {
        _cid = cid;
        _type = GROUP_TITLE_GROUP_DETAILS;
    }
    return self;
}

-(instancetype)initWithCid:(NSString *)cid type:(GROUP_TITLE_TYPE)titleType
{
    self = [super init];
    if (self) {
        _cid = cid;
        _type = titleType;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (_type == GROUP_TITLE_ART_TALKS) {
        self.title = NSLocalizedString(@"Art Talks", nil);
    } else self.title = NSLocalizedString(@"Group Details", nil);
    self.heightForFirstSectionCell = 300.0f;
    self.heightForSecondSectionCell = 0.1f;
    [self ig_setupRightButtonItemWithTitle:@"" image:[UIImage imageNamed:@"community_rightBar"] highLightedImage:[UIImage imageNamed:@"community_rightBar"]];
    
    [self addBottomView];
    
    self.lastTimeDate = @"0";
    self.page = 1;
    self.communityDetailApi = [[IGCommunityDetailApi alloc] initWithCid:self.cid lastTimeDate:self.lastTimeDate];
    self.communityDetailApi.page = self.page;
    self.requestApi = self.communityDetailApi;
    
    __weak typeof(self) weakSelf = self;
    [self.tableView ig_setHeaderWithRefreshingBlock:^{
        weakSelf.lastTimeDate = @"0";
        weakSelf.page = 1;
        weakSelf.communityDetailApi.lastTimeDate = weakSelf.lastTimeDate;
        weakSelf.communityDetailApi.page = weakSelf.page;
        
        [weakSelf requestData];
    }];
    
    [self requestData];
}
    
- (void)addBottomView {
    UIButton *pubBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    pubBtn.tag = 100;
//    [pubBtn setTitle:@"发布新话题" forState:UIControlStateNormal];
    [pubBtn setTitle:NSLocalizedString(@"Post New Topic", nil) forState:UIControlStateNormal];
    pubBtn.backgroundColor = [UIColor appColor];
    [self.view addSubview:pubBtn];
    
    [pubBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(0);
        make.height.mas_equalTo(0);
    }];
    
    __weak typeof(self) weakSelf = self;
    [pubBtn setTapActionWithBlock:^{
        IGIssueTopicVC *topicVC = [[IGIssueTopicVC alloc] initWithCommunityModel:weakSelf.communityModel];
        topicVC.autoRefresh = ^{
            [weakSelf.tableView ig_beginHeaderRefreshing];
        };
        [UIViewController ig_pushViewController:topicVC animated:YES];
    }];
}

- (void)ig_rightButtonPressed:(id)sender {
    [self.view endEditing:YES];
    
    YXScrollowActionSheet *cusSheet = [[YXScrollowActionSheet alloc] init];
    IGShareModel *shareModel = [self.communityModel getShareModel];
    cusSheet.shareModel = shareModel;
    [cusSheet show];
}

- (void)requestData {
    __weak typeof(self) weakSelf = self;
    [self.communityDetailApi startWithDecodeClass:[IGCommunityDetailResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        [weakSelf.tableView ig_endHeaderRefreshing];
        [weakSelf.tableView ig_endFooterRefreshing];
        if (responseObject) {
            IGCommunityDetailResp *resp = responseObject;
            IGCommunityDetailModel *model = resp.data;
            
            NSMutableArray *tmpTopicArr = model.topics;
            if (tmpTopicArr && tmpTopicArr.count > 0) {
                [weakSelf setupFooter];
            } else {
                [weakSelf.tableView ig_endFooterRefreshingWithNoMoreData];
            }
            
            if (weakSelf.page == 1) {
                weakSelf.communityModel = model.circle;
                weakSelf.dataSource = tmpTopicArr;
            } else {
                [weakSelf.dataSource addObjectsFromArray:tmpTopicArr];
            }
            
            weakSelf.lastTimeDate = model.lastTimeDate;
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableView reloadData];
                if (weakSelf.dataSource.count > 0 || weakSelf.communityModel) {
                    UIButton *pubBtn = (UIButton *)[weakSelf.view viewWithTag:100];
                    [pubBtn mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.height.mas_equalTo(44);
                    }];
                }
            });
        }
    }];
}
    
- (void)focusCircleRequest {
    __weak typeof(self) weakSelf = self;
    IGCommonApi *commonApi = [[IGCommonApi alloc] initWithApiType:IGiGalleryApiTypeCircleFocusCircle];
    commonApi.circleId = self.cid;
    [commonApi startWithDecodeClass:[IGCommonResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            weakSelf.communityModel.isFocus = [weakSelf.communityModel.isFocus isEqualToString:@"1"]?@"0":@"1";
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([weakSelf.communityModel.isFocus isEqualToString:@"1"]) {

                } else {

                }
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
                [weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            });
        }
    }];
}
    
- (void)setupFooter {
    __weak typeof(self) weakSelf = self;
    [self.tableView ig_setFooterWithRefreshingBlock:^{
        weakSelf.page++;
        weakSelf.communityDetailApi.page = weakSelf.page;
        weakSelf.communityDetailApi.lastTimeDate = weakSelf.lastTimeDate;
        
        [weakSelf requestData];
    }];
}

#pragma mark - UITableViewDelegate, UITableViewDataSource
- (UITableViewCell *)customFirstSectionCell:(UITableView *)tableView {
    IGCommunityDetailHeaderCell *cell = [IGCommunityDetailHeaderCell cellWithTableView:tableView];
    [cell configCellWithModel:self.communityModel];
    __weak typeof(self) weakSelf = self;
    cell.focusCircle = ^{
        [weakSelf focusCircleRequest];
    };
    
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (self.communityModel && self.dataSource.count>0) {
        return 2;
    } else if(self.communityModel) {
        return 1;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        __weak typeof(self) weakSelf = self;
        CGFloat h = [IGCommunityDetailHeaderCell hyb_heightForTableView:tableView config:^(UITableViewCell *sourceCell) {
            IGCommunityDetailHeaderCell *cell = (IGCommunityDetailHeaderCell *)sourceCell;
            [cell configCellWithModel:weakSelf.communityModel];
        } cache:^NSDictionary *{
            NSDictionary *cache = @{kHYBCacheUniqueKey : weakSelf.communityModel.cid,
                                    kHYBCacheStateKey  : @"",
                                    kHYBRecalculateForStateKey : @(weakSelf.communityModel.shouldUpdateCache)};
            weakSelf.communityModel.shouldUpdateCache = YES;
            return cache;
        }];
        return h;
    } else {
        return [super tableView:tableView heightForRowAtIndexPath:indexPath];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        return 10.f;
    }
    return 0.1f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isShowKeyBoard) {
        [self.view endEditing:YES];
        return;
    }
    if (indexPath.section == 0) {
        return;
    }
    IGTopicModel *topicModel = [self.dataSource objectAtIndex:indexPath.row];
    
    IGTopicDetailVC *detailVC = [[IGTopicDetailVC alloc] initWithTopicId:topicModel.tid];
    [UIViewController ig_pushViewController:detailVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
